#!/usr/bin/env python
# Diff two arbitrary-sized sorted files, generating corresponding manifests of missing files.

import sys

class InFile(object):
    def __init__(self, src_fp, out_fp):
        self.src = src_fp
        self.out = out_fp
        self.next()
        self.found_any = False

    def next(self):
        line = self.src.readline()
        if line.endswith('\n'):
            line = line[:-1]
        self.line = line
        return self.line

    def end(self):
        "No opponent remains, finish off this diff solo."
        while self.line:
            self.found()
            self.next()

    def found(self):
        "Do something with a diff found for this file."
        prefix = '\n'
        if not self.found_any:
            prefix = ''
        self.found_any = True
        self.out.write(prefix + self.line)

def megadiff(*files):
    """
    Given a list of fp pairs (in, out), perform a diff between each in file, 
    writing the result to each out file.
    
    NOTE: Currently only supports 2 files
    """
    if len(files) != 2:
        raise TypeError('megadiff() only supports two file pairs')
    
    a = InFile(*files[0])
    b = InFile(*files[1])
    
    while a.line and b.line:
        while a.line != b.line and a.line and b.line:
            if a.line < b.line:
                a.found()
                a.next()
            elif b.line < a.line:
                b.found()
                b.next()
        a.next()
        b.next()

    # Done
    if a.line:
        a.end()
    if b.line:
        b.end()

def main():
    args = sys.argv

    a = open(args[1], 'r'), open(args[1] + '.extra', 'w')
    b = open(args[2], 'r'), open(args[2] + '.extra', 'w')

    megadiff(a, b)

if __name__ == '__main__':
    main()
